﻿using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

    public GameObject startMenu;
    public GameObject gameUI;
    public GameObject whiteBlock;
    public GameObject greyBlock;
    public GameObject darkBlueBlock;
    public GameObject lightBlueBlock;
    public GameObject greenBlock;
    ArrayList blocks;
    public GameObject container;
    public static int score =0;
    public static bool isStarted = false;

	// Use this for initialization
	void Start () {
        container = gameObject.transform.FindChild("container").gameObject;
        blocks = new ArrayList();
    }
	
	// Update is called once per frame
	void Update () {
	
	}

    public void EnterGame()
    {
        startMenu.SetActive(false);
        gameUI.SetActive(true);
        CreateRandomBlock();
        isStarted = true;
    }

    public void ExitGame()
    {
        DestroyBlock();
        startMenu.SetActive(true);
        gameUI.SetActive(false);
        isStarted = false;
        score = 0;
    }

    public void CreateRandomBlock()
    {
        for(int rowIndex = 0; rowIndex < 4; rowIndex++)
        {
            CreateBlock(rowIndex);
            blocks.Clear();
        }
        
    }

    public void CreateBlock(int rowIndex)
    {
        int randomBlockNum = Random.Range(0, 5);
        GameObject o = null;
        switch (randomBlockNum)
        {
            case 0:
                o = Instantiate(whiteBlock) as GameObject;
                break;
            case 1:
                o = Instantiate(greyBlock) as GameObject;
                break;
            case 2:
                o = Instantiate(darkBlueBlock) as GameObject;
                break;
            case 3:
                o = Instantiate(lightBlueBlock) as GameObject;
                break;
            case 4:
                o = Instantiate(greenBlock) as GameObject;
                break;
            default:
                break;
        }
        o.transform.parent = container.transform;
        Block block = o.GetComponent<Block>();
        int columnIndex = Random.Range(0, 4);
        block.MoveBlock(columnIndex, rowIndex);
    }

    public void DestroyBlock()
    {
        for(int i=0;i< container.transform.childCount; i++)
        {
            Destroy(container.transform.GetChild(i).gameObject);
        }
    }

    public void Score()
    {

    }

    public void SelectBlock()
    {
        for (int i = 0; i < container.transform.childCount; i++)
        {
            Block b = container.transform.GetChild(i).gameObject.GetComponent<Block>();
            b.MoveDown();
            if (b.rowIndex < 0)
            {
                Destroy(b.gameObject);
                CreateBlock(4);
            }
        }
    }
}
